package base.stream.normal;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class FlatMapDemo {
    public static void main(String[] args) {
        Customer sheridan = new Customer("Sheridan");
        Customer ivanova = new Customer("Ivanova");
        Customer garibaldi = new Customer("Garibaldi");

        sheridan.addOrder(new Order(1)).addOrder(new Order(2)).addOrder(new Order(3));

        ivanova.addOrder(new Order(4)).addOrder(new Order(5));

        List<Customer> customers = Arrays.asList(sheridan, ivanova, garibaldi);

        // 空集合也会返回
        customers.stream().map(Customer::getOrders).forEach(System.out::println);

        // 空流也会返回
        customers.stream().map(customer -> customer.getOrders().stream()).forEach(System.out::println);

        // flatMap 方法从各个流中删除每个元素并将它们添加到输出，生成的元素被“展平”为一个新的流

        customers.stream().flatMap(customer -> customer.getOrders().stream()).forEach(System.out::println);


        Stream<String> first = Stream.of("a", "b", "c").parallel();
        Stream<String> second = Stream.of("x", "y", "z");
        Stream<String> third = Stream.of("alpha", "beta", "gamma");
        Stream<String> fourth = Stream.empty();

        // 在合并多个流时，使用 flatMap 方法成为一种自然而然的解决方案
        List<String> stringList = Stream.of(first, second, third, fourth)
                .flatMap(Function.identity())
                .collect(Collectors.toList());

        stringList.forEach(System.out::println);

        // 并行流处理
        Stream<String>total = Stream.of(first, second, third, fourth)
                .flatMap(Function.identity());
        total = total.parallel();
        assertTrue(total.isParallel());
    }
}
